<template>
  <a-card :bordered="false" :title="$t('all.autotext1369')" @back="() => $router.go(-1)">
    <div>
      <a-form-model layout="inline">
        <!-- 基本信息 -->
        <a-row :gutter="[24, 12]">
          <a-col class="gutter-row" :span="8">
            <a-form-model-item :label="$t('all.autotext10') + ':'" labelAlign="left">{{ $store.getters.userInfo.userName }}</a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item :label="$t('all.autotext1091')" labelAlign="left">{{ date }}</a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item :label="$t('all.autotext1005')" labelAlign="left">{{ Number(totalAmt) ? Number(totalAmt).toFixed(2) : '0.00' }}</a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item :label="$t('all.autotext149')" labelAlign="left"><span>{{ $route.query.pname }}</span></a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item :label="$t('all.autotext455')" labelAlign="left" :required="true">
              <a-select
                :default-value="$t('all.autotext1348')"
                style="width: 183px"
                @change="handleCenterChange"
                show-search
                :filter-option="filterOption"
                v-model="centerId"
              >
                <a-select-option v-for="item in centerList" :key="item.id" :value="item.id">
                  <span :title="item.researchCenterNo + '-' + item.orgName">
                    {{ item.researchCenterNo }}-{{ item.orgName }}
                  </span>
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item :label="$t('all.autotext1134')" labelAlign="left" :required="true">
              <a-select
                :default-value="$t('all.autotext1348')"
                style="width: 183px"
                @change="handleVersionChange"
                v-model="versionId"
              >
                <a-select-option v-for="item in versionList" :key="item.id" :value="item.id">
                  <span :title="item.name">
                    {{ item.name }}
                  </span>
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item :label="$t('all.autotext507')" :required="true">
              <a-select
                v-model="ptsTypeId"
                :placeholder="$t('all.autotext930')"
                style="width: 183px"
                @change="handlePtsChange"
              >
                <a-select-option v-for="item in ptsTypesList" :key="item.id" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item :label="$t('all.autotext1357')" labelAlign="left" :required="true">
              <a-select
                :default-value="$t('all.autotext1348')"
                style="width: 183px"
                show-search
                :filter-option="filterOption"
                @change="handlePersonChange"
                v-model="personName"
              >
                <a-select-option v-for="item in personList" :key="item.ptsNo" :value="item.ptsNo">
                  {{ $t('all.autotext1565') + item.ptsNo }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8" v-if="offline === 1">
            <a-form-model-item :label="$t('all.autotext473')" labelAlign="left" :required="true">
              <a-select
                :default-value="$t('all.autotext1348')"
                style="width: 183px"
                @change="handleAccountChange"
                v-model="accountId"
              >
                <a-select-option v-for="item in accountList" :key="item.id" :value="item.id">
                  <span :title="`${$options.filters.enumValueByKey(item.bankType, $const.BANK_TYPE)} ${item.bankCardNo}`">
                    {{ item.bankType | enumValueByKey($const.BANK_TYPE) }} {{ item.bankCardNo }}
                  </span>
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="8">
            <a-form-model-item :label="$t('all.autotext74')" labelAlign="left">
              <span>{{ moneyType }}</span>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="24" v-if="OriginFeeApplyInfo.length">
            <a-form-model-item :label="$t('all.autotext1745')" labelAlign="left" :required="true">
              <a
                v-for="(item, i) in OriginFeeApplyInfo"
                :key="i"
                style="margin-right:10px;"
                @click="handleOrigin(item)"
              >
                {{ item.applyNo }}
              </a>
            </a-form-model-item>
          </a-col>
          <a-col class="gutter-row" :span="24">
            <a-form-model-item :label="$t('all.autotext550')" labelAlign="left" :required="true">
              <a-textarea
                :placeholder="$t('all.autotext1371')"
                style="width:905px"
                :rows="3"
                v-model="applyReason"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- 费用事项 -->
        <FeeEdit
          :mattersItem="mattersItem"
          @updateFee="updateFee"
          :stages="stages"
          :type="2"
          :ptsId="ptsId"
          :ptsTypeId="ptsTypeId"
          :versionId="versionId"
          :researchId="this.centerId"
          ref="fee"
        />
        <!-- 审批预览 -->
        <ApprovePreview
          :nodes="filterFlowNodes"
          :offline="offline"
          @assign="updateAssign"
          ref="approvePreview"
          :approveUsers="approveUsers"
        />
        <a-row :gutter="[24, 12]">
          <a-col class="gutter-row" :span="14">
            <div style="padding-top:20px">
              <a-button
                style="margin-left: 10px"
                :loading="saveDraftLoading"
                :disabled="storeAndSubmitButtonState"
                @click="submitDraft"
              >
                {{ $t('all.autotext321') }}
              </a-button>
              <a-button
                type="primary"
                style="margin-left: 10px"
                :disabled="storeAndSubmitButtonState"
                :loading="submitting"
                @click="identityShow"
              >
                {{ $t('all.autotext218') }}
              </a-button>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <DetailView ref="detailView" />
    <a-modal
      :title="$t('all.autotext730')"
      :visible="visibleDraft"
      :closable="false"
      :maskClosable="false"
      :oktext="$t('all.autotext919')"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <p>{{ $t('all.autotext414') }}</p>
    </a-modal>
    <identityCheck ref="identityRef" :content="$t('all.autotext1564')" @ok="submit" />
    <reModal ref="reModal" />
  </a-card>
</template>
<script>
import FeeEdit from '../FeeEdit'
import ApprovePreview from '../components/approvePreview.vue'
import moment from 'moment'
import identityCheck from '@views/cost-auditing/components/identityCheck'
import reModal from '../components/reModal'
import DetailView from '@/views/cost-auditing/detail.vue'

import {
  selectSubjectCenter,
  selectSubjectPerson,
  selectSubjectAccount,
  getVersionList,
  feeApplyCommitForCRC,
  preCheckForCommit,
  getFlowInfo,
  listTeamForPtNo,
  feeApplySaveDraft,
  getDraftDetail,
  getApplySubmitDetail,
  getOriginFeeApplyInfo
} from '@/api/cost/cost'
import { getApprovalDetail } from '@/api/overview/approval'
import { getVisitStagesByVersion } from '@/api/overview/visit'
import { getPtsTypes } from '@api/overview/cost'
// import { borderTopRightRadius } from 'html2canvas/dist/types/css/property-descriptors/border-radius'

export default {
  props: {},
  components: { FeeEdit, ApprovePreview, identityCheck, reModal, DetailView },
  data () {
    return {
      visibleDraft: false, // 保存草稿弹窗
      draftFlag: false, // 标识是否启用草稿
      proFlowId: 1,
      stages: [],
      ptsTypeId: undefined,
      formList: [],
      fileList: [],
      ptsTypesList: [],
      moneyType: 'RMB',
      applyReason: '',
      type: 2,
      date: moment().format('YYYY-MM-DD'),
      totalAmt: 0,
      centerList: [], // 中心列表
      personList: [], // 收款人员
      accountList: [], // 收款账号
      versionList: [], // 访视版本
      versionId: null,
      centerId: null,
      projectId: null,
      personId: null,
      accountId: null,
      personName: '',
      submitting: false,
      mattersList: [],
      mattersItem: [], // 保存到草稿箱里的费用事项
      saveDraftLoading: false,
      personMap: {},
      allFlowNodes: [], // 全部审批流程
      filterFlowNodes: [], // 过滤后的审批流程
      assignInfo: {}, // 审批人信息
      approveUsers: {}, // 审批人
      ptsId: null, // 受试者id
      offline: 1, // 是否为系统支付
      OriginFeeApplyInfo: [],
      storeAndSubmitButtonState: false
    }
  },
  provide () {
    return {
      getStoreAndSubmitButtonState: this.getStoreAndSubmitButtonState
    }
  },
  watch: {
    centerId (val) {
      this.getFlow()
    }
  },
  async created () {
    const pd = localStorage.getItem('CURRENT_PROID')
    if (pd) {
      this.projectId = parseInt(pd)
    }
    this.getDraft()
    await this.getCenterList()
    await this.getVersionList()
    // this.getMattersList()
    this.ptsTypesList = await getPtsTypes({ proId: this.projectId })
    if (this.$route.query.ptsTypeRoleId) this.ptsTypeId = Number(this.$route.query.ptsTypeRoleId)
    if (this.$route.query.costId) {
      this.getApply()
      this.getOriginInfo()
    }
  },
  // 销毁监听事件
  destroyed () {
    this.draftFlag = false
  },
  methods: {
    async getOriginInfo () {
      const res = await getOriginFeeApplyInfo({ costId: this.$route.query.costId })
      this.OriginFeeApplyInfo = res
    },
    handleOk () {
      // 回填数据
      this.draftFlag = true
      this.fillBackData()
      this.visibleDraft = false
    },
    handleCancel () {
      this.draftFlag = false
      this.visibleDraft = false
    },
    getDraft () {
      getDraftDetail({
        proId: this.projectId,
        type: '2'
      }).then(({ haveDraft, feeApplyJson }) => {
        if (haveDraft && !this.$route.query.costId) {
          this.visibleDraft = true
        }
        this.feeApplyJson = JSON.parse(feeApplyJson)
      })
    },
    getApply () {
      getApplySubmitDetail({
        id: this.$route.query.costId
      }).then(res => {
        this.fillBackData1(res)
      })
    },
    /*
    * 回填草稿里数据
    * */
    async fillBackData () {
      const {
        orgId,
        orgDeptName,
        bankId,
        applyReason,
        visitId,
        ptsNo,
        ptsTypeId,
        fileArray
      } = this.feeApplyJson.feeApply
      if (orgId) {
        this.fillCenterData(orgId)
        if (!this.centerId) return
        await this.getFlow()
        await this.getPersonList()
      }
      if (ptsNo) {
        const obj = this.personList.find(v => v.ptsNo === ptsNo)
        if (obj.ptsTypeRoleId && this.checkDataExistsInList(obj.ptsTypeRoleId, this.ptsTypesList, 'id')) {
          this.ptsTypeId = obj.ptsTypeRoleId
        }
        this.ptsId = obj.id
        this.personId = ptsNo
        await this.getAccountList()
        await this.getApproveUsers()
      }
      if (visitId) {
        this.stages = await getVisitStagesByVersion({ versionId: visitId })
        if (this.checkDataExistsInList(visitId, this.versionList, 'id')) {
          this.versionId = visitId
        }
      }
      // 中心存在才能再次填充人员和账号，中心都不存在了，人员也无法获取
      if (this.centerName) {
        this.fillPersonNameData(ptsNo)
        if (this.personName) {
          this.fillAccountData(bankId)
        }
      }
      this.orgDeptName = orgDeptName
      this.applyReason = applyReason
      this.ptsTypeId = ptsTypeId

      if (fileArray) {
        this.fileList = JSON.parse(fileArray)
        this.$refs.fee.backFileList(this.fileList)
      }

      if (this.feeApplyJson.feeApplyDetails) {
        const mattersItem = JSON.parse(this.feeApplyJson.feeApplyDetails)
        mattersItem.forEach(item => {
          item.fileList = item.fileArr.map(e => {
            return {
              fileName: e.fileName,
              fileUrl: e.afterUrl || e.originalUrl
            }
          })
          item.fileArr = JSON.stringify(item.fileArr)
        })
        this.fillMatterItem(mattersItem)
      }
    },
    fillMatterItem (list) {
      const availableItem = list.filter(e => {
        return this.mattersList.some(item => item.id === e.proFlowFeeCategoryId)
      })
      // this.mattersItem = availableItem
      this.mattersItem = availableItem.length ? availableItem : list
    },
    /*
    * 回填草稿里数据-- 驳回数据
    * */
    async fillBackData1 (data) {
      const {
        orgId,
        orgDeptName,
        bankId,
        applyReason,
        visitId,
        ptsNo,
        ptsTypeId
      } = data
      if (orgId) {
        this.fillCenterData(orgId)
        if (!this.centerId) return
        await this.getFlow()
        await this.getPersonList()
      }
      if (ptsNo) {
        const obj = this.personList.find(v => v.ptsNo === ptsNo)
        if (obj.ptsTypeRoleId && this.checkDataExistsInList(obj.ptsTypeRoleId, this.ptsTypesList, 'id')) {
          this.ptsTypeId = obj.ptsTypeRoleId
        }
        this.ptsId = obj.id
        this.personId = ptsNo
        await this.getAccountList()
        await this.getApproveUsers()
      }
      if (visitId) {
        this.stages = await getVisitStagesByVersion({ versionId: visitId })
        if (this.checkDataExistsInList(visitId, this.versionList, 'id')) {
          this.versionId = visitId
        }
      }
      // 中心存在才能再次填充人员和账号，中心都不存在了，人员也无法获取
      if (this.centerName) {
        this.fillPersonNameData(ptsNo)
        if (this.personName) {
          this.fillAccountData(bankId)
        }
      }
      this.orgDeptName = orgDeptName
      this.applyReason = applyReason
      this.ptsTypeId = ptsTypeId

      if (data.fileArray) {
        this.fileList = JSON.parse(data.fileArray)
        this.$refs.fee.backFileList(this.fileList)
      }

      if (data.list) {
        this.fillMatterItem(data.list)
      }
    },
    checkDataExistsInList (id, list, prop) {
      return list.some(e => e[prop] === id)
    },
    fillCenterData (orgId) {
      if (this.checkDataExistsInList(orgId, this.centerList, 'id')) {
        this.centerName = orgId
        this.centerId = orgId
      }
    },
    fillPersonNameData (ptsNo) {
      if (this.checkDataExistsInList(ptsNo, this.personList, 'ptsNo')) {
        this.personName = ptsNo
      }
    },
    fillAccountData (bankId) {
      if (this.checkDataExistsInList(bankId, this.accountList, 'id')) {
        this.accountId = bankId
      } else {
        if (this.accountList.length) this.accountId = this.accountList[0].id
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    updateFee (val, totalAmt, fileList) {
      this.formList = val
      this.fileList = fileList
      this.totalAmt = totalAmt
      this.updateFlowNodes()
    },
    // 请求中心列表
    getCenterList () {
      selectSubjectCenter({ proId: this.projectId })
        .then(res => {
          this.centerList = res
          if (this.$route.query.reId) {
            this.centerId = Number(this.$route.query.reId)
            this.getPersonList()
          }
        })
        .catch(() => {})
    },
    // 请求收款人员列表
    async getPersonList () {
      const res = await selectSubjectPerson({
        ptsTypeId: this.ptsTypeId,
        proId: this.projectId,
        researchId: this.centerId
      })
      // 去掉状态是已退出的
      this.personList = res
      res.forEach(item => {
        this.personMap[item.ptsNo] = item
        if (this.$route.query.ptsNo === item.ptsNo) {
          this.personName = this.$route.query.ptsNo
          this.handlePersonChange(this.personName)
        }
      })
    },
    // 请求收款账户列表
    getAccountList () {
      const queryObj = {}
      queryObj.ptsNo = this.personId
      queryObj.proId = this.projectId
      return selectSubjectAccount({ ...queryObj })
        .then(res => {
          const arr = res.filter((e) => e.defaultCard === 1)
          this.accountList = arr
          if (arr && arr[0] && arr[0].id) {
            this.accountId = arr[0].id
            // this.getPersonList()
          }
        })
        .catch(() => {})
    },
    handlePtsChange (value) {
      this.getPersonList()
      this.personId = null
      this.personName = ''
      this.accountId = null
      this.personList = []
      this.accountList = []
      if (this.formList.length > 0) {
        this.formList.forEach(item => {
          item.applyType = null
          item.feeList = null
          item.visitRecordId = null
          item.visitRecordInfo = null
          if (item._originalData) {
            item._originalData.visitRecordId = null
            item._originalData.visitRecordInfo = null
          }
        })
      }
    },
    // 版本列表下拉改变
    async handleVersionChange (value) {
      // 阶段和版本关联 版本一旦改变，将费用事项所有行的访视阶段全部置空
      // if (this.formList.length > 0) {
      //   this.formList.forEach(item => {
      //     item.applyType = null
      //     item.feeList = null
      //     item.visitRecordId = null
      //     item.visitRecordInfo = null
      //     if (item._originalData) {
      //       item._originalData.visitRecordId = null
      //       item._originalData.visitRecordInfo = null
      //     }
      //   })
      // }
      this.$refs.fee.clearList()
      this.updateFee([], 0)
      // 受试者根据方式版本获取访视阶段
      this.stages = await getVisitStagesByVersion({ versionId: value })
    },
    // 中心列表下拉改变
    handleCenterChange (value) {
      this.centerId = value
      this.personId = null
      this.personName = ''
      this.accountId = null
      this.personList = []
      this.accountList = []
      this.$refs.approvePreview.values = {}
      this.getPersonList()
    },
    // 收款人员列表下拉改变
    handlePersonChange (value) {
      const obj = this.personList.find(v => v.ptsNo === value)
      this.ptsId = obj.id
      this.ptsTypeId = obj.ptsTypeRoleId
      this.personId = value
      this.accountId = null
      this.accountList = []
      this.getAccountList()
      this.getApproveUsers()
    },
    // 账户列表下拉改变
    handleAccountChange (value) {
      // this.accountId = value
    },
    // 报销类目列表
    async getMattersList () {
      if (!this.projectId) return
      const res = await getApprovalDetail({
        proId: this.projectId,
        type: 2
      })
      this.proFlowId = res.id
    },
    // 访视版本列表
    getVersionList () {
      // 请求时传参： 临床试验方案编号
      getVersionList({ proId: this.projectId })
        .then(res => {
          this.versionList = res
          if (res.length === 1) {
            this.versionId = res[0].id
            this.handleVersionChange(res[0].id)
          }
        })
    },
    // 获取审批人
    async getApproveUsers () {
      const res = await listTeamForPtNo({
        ptsId: this.ptsId,
        ptsNo: this.personId,
        proId: this.projectId
      })
      this.approveUsers = res
    },
    // 获取审批流
    async getFlow () {
      if (this.isGetFlow) return
      this.isGetFlow = true
      try {
        const res = await getFlowInfo({
          proId: this.projectId,
          researchId: this.centerId,
          type: this.type
        })
        // const res = await getFlowInfo({
        //   proId: 30496,
        //   researchId: 30341,
        //   type: 1
        // })

        let { nodeList, id, offline, feeCategoryList } = res
        feeCategoryList.forEach(i => {
          i.editable = false
          i.fileList = []
          i.amt = i.defaulted ? i.amt : ''
        })
        this.proFlowId = id
        this.mattersList = feeCategoryList
        this.offline = offline
        nodeList.sort((a, b) => parseInt(a.code) - parseInt(b.code))
        this.allFlowNodes = nodeList
        this.filterFlowNodes = nodeList.filter(item => item.actionType !== 2 && !item.applyType)
        if (this.formList.length > 0) {
          this.updateFlowNodes()
        }
      } catch (err) {
        this.allFlowNodes = []
        this.filterFlowNodes = []
      } finally {
        this.isGetFlow = false
      }
    },
    // 更新审批流
    updateFlowNodes () {
      const addApplyTypes = this.formList.map(item => item.applyType)
      this.filterFlowNodes = this.allFlowNodes.filter(item => {
        if (!item.applyType && item.actionType !== 2) {
          return true
        }
        if (!item.applyType) return false
        const itemApplyTypes = item.applyType.split(',')
        return (itemApplyTypes.some(type => addApplyTypes.includes(type)) && item.actionType !== 2)
      })
    },
    // 选择审批人
    updateAssign (info) {
      this.assignInfo = info
    },
    /**
     * 获取脱敏后的文件地址
     * @param item 文件对象
     * @return {*|string}
     */
    // getDesensitizedFileUrl (item) {
    //   if (!item.fileList || !item.fileList.length) return item.fileUrl || ''
    //   if (item.fileList.length === 1) return (item.fileList[0].afterFileUrl || item.fileList[0].fileUrl)
    //   return item.fileList?.reduce((pre, cur) => {
    //     return pre ? pre + ',' + (cur.afterFileUrl || cur.fileUrl) : (cur.afterFileUrl || cur.fileUrl)
    //   }, '')
    // },
    getFileArr (item) {
      if (!Array.isArray(item)) return []
      return item.map(e => ({
        afterUrl: e.afterFileUrl || '',
        originalUrl: e.fileUrl || '',
        fileName: e.fileName,
        type: this.$const.UPLOAD_FILE_TYPE.FEE_DETAIL.value
      }))
    },
    async identityShow () {
      if (!this.centerId || !this.versionId || !this.personName || !this.applyReason || (this.offline === 1 && !this.accountId) || !this.ptsTypeId) {
        this.$message.error(this.$t('all.autotext381'))
        return false
      }
      const target = this.formList.find(item => item.editable)
      if (target) {
        this.$message.error(this.$t('all.autotext1293'))
        return false
      }
      if (this.formList.length < 1) {
        this.$message.error(this.$t('all.autotext1050'))
        return false
      }
      const applyTypeItem = this.formList.find(item => !item.applyType)
      if (applyTypeItem) {
        this.$message.error(this.$t('all.autotext1471'))
        return
      }
      // 访视版本下拉框一旦变化，会将原来添加好的访视阶段置空，故需用户重新编辑所有的访视阶段
      const visitRecordIdItem = this.formList.find(item => item.visitRecordId == null)
      if (visitRecordIdItem) {
        this.$message.error(this.$t('all.autotext1148'))
        return
      }
      const amountItem = this.formList.find(item => !item.amount)
      if (amountItem) {
        this.$message.error(this.$t('all.autotext1061'))
        return
      }
      let assignInfoValid = true
      if (this.assignInfo && Object.keys(this.assignInfo).length) {
        assignInfoValid = Object.values(this.assignInfo).every(item => item !== '')
      }
      if (!assignInfoValid) {
        this.$message.error(this.$t('all.autotext270'))
        return false
      }
      const errIndex = this.fileList.findIndex(item => [0, 2, 4, 6].includes(item.fileStatus))
      const reUploadIndex = this.fileList.findIndex(item => [1].includes(item.fileType))
      if (errIndex > -1) {
        this.$message.error(this.$t('all.autotext1819'))
        return
      }
      if (reUploadIndex > -1) {
        this.$message.error(this.$t('all.autotext1820'))
        return
      }
      const costDetails = []
      for (const k of this.formList) {
        const fee = k?.feeList?.find(v => v.id === k.manageCostId)
        costDetails.push({
          proFlowFeeCategoryId: k.manageCostId,
          applyType: k.applyType,
          amount: k.amount,
          apv: fee ? fee.apv : k.apv,
          defaultAmt: k.defaultAmt,
          defaultBool: fee ? fee.defaulted : k.defaultBool,
          happenDate: k.happenDate,
          supply: 0,
          supplyRemark: k.supplyRemark,
          visitRecordId: k.visitRecordId,
          visitRecordInfo: k.visitRecordInfo,
          // fileUrl: this.getDesensitizedFileUrl(k),
          fileUrl: k.fileUrl,
          fileArr: this.getFileArr(k.fileList),
          costMin: k.costMin,
          costMax: k.costMax
          // comment: k.comment
        })
        if (!k.applyType) {
          this.$message.error(this.$t('all.autotext1471'))
          return
        }
        if (k.amount === '' || k.amount === null || k.amount === undefined) {
          this.$message.error(this.$t('all.autotext500'))
          return
        }
      }
      const personObj = this.personMap[this.personName]
      let fileHash = []
      this.fileList.forEach(e => {
        if (e.fileHash) fileHash.push(e.fileHash)
      })
      const subData = {
        proId: this.projectId,
        proFlowId: this.proFlowId,
        orgId: this.centerId,
        userNo: this.personId,
        type: this.type,
        bankId: this.accountId,
        moneyType: this.moneyType,
        applyReason: this.applyReason,
        fileArray: JSON.stringify(this.fileList),
        fileHash: fileHash.join(','),
        feeApplyDetails: JSON.stringify(costDetails),
        ptsTypeId: this.ptsTypeId,
        ptsTypeIdDesc: this.ptsTypesList.find(item => {
          return item.id === this.ptsTypeId
        })?.description,
        ptsId: personObj ? personObj.id : '',
        ptsNo: personObj ? personObj.ptsNo : '',
        ptsName: personObj ? personObj.ptsName || personObj.bankName : '',
        visitId: this.versionId,
        assignInfo: JSON.stringify(this.assignInfo),
        originInfo: JSON.stringify(this.OriginFeeApplyInfo)
      }
      const check = await preCheckForCommit(subData)
      if (check.flag) {
        const that = this
        this.$confirm({
          title: this.$t('all.autotext730'),
          content: (h) => {
            return h('div', check.message.map(node => h('p', node)))
          },
          onOk () {
            that.$refs.identityRef.open()
          }
        })
      } else {
        this.$refs.identityRef.open()
      }
    },
    // 点击提交
    async submit () {
      const costDetails = []
      for (const k of this.formList) {
        const fee = k?.feeList?.find(v => v.id === k.manageCostId)
        costDetails.push({
          proFlowFeeCategoryId: k.manageCostId,
          applyType: k.applyType,
          amount: k.amount,
          apv: fee ? fee.apv : k.apv,
          defaultAmt: k.defaultAmt,
          defaultBool: fee ? fee.defaulted : k.defaultBool,
          happenDate: k.happenDate,
          supply: 0,
          supplyRemark: k.supplyRemark,
          visitRecordId: k.visitRecordId,
          visitRecordInfo: k.visitRecordInfo,
          // fileUrl: this.getDesensitizedFileUrl(k),
          fileUrl: k.fileUrl,
          fileArr: this.getFileArr(k.fileList),
          costMin: k.costMin,
          costMax: k.costMax
          // comment: k.comment
        })
      }

      const personObj = this.personMap[this.personName]
      this.submitting = true
      let fileHash = []
      this.fileList.forEach(e => {
        if (e.fileHash) fileHash.push(e.fileHash)
      })
      const subData = {
        proId: this.projectId,
        proFlowId: this.proFlowId,
        orgId: this.centerId,
        userNo: this.personId,
        type: this.type,
        bankId: this.accountId,
        moneyType: this.moneyType,
        applyReason: this.applyReason,
        fileArray: JSON.stringify(this.fileList),
        fileHash: fileHash.join(','),
        feeApplyDetails: JSON.stringify(costDetails),
        ptsTypeId: this.ptsTypeId,
        ptsTypeIdDesc: this.ptsTypesList.find(item => {
          return item.id === this.ptsTypeId
        })?.description,
        ptsId: personObj ? personObj.id : '',
        ptsNo: personObj ? personObj.ptsNo : '',
        ptsName: personObj ? personObj.ptsName || personObj.bankName : '',
        visitId: this.versionId,
        assignInfo: JSON.stringify(this.assignInfo),
        originInfo: JSON.stringify(this.OriginFeeApplyInfo)
      }
      feeApplyCommitForCRC(subData)
        .then(res => {
          this.submitting = false
          const { newFeeApply, msg } = res
          if (newFeeApply.duplicateCheck) {
            this.$refs.reModal.open(newFeeApply)
            return
          }
          if (!msg) {
            this.$message.success(this.$t('all.autotext1401'))
          } else {
            this.$message.warning(msg)
          }
          this.$router.push({ name: 'SubjectList' })
        })
        .catch(() => {
          this.submitting = false
        })
    },
    // 保存草稿
    submitDraft () {
      const costDetails = []
      for (const k of this.formList) {
        const fee = k.feeList?.find(v => v.id === k.manageCostId || v.proFlowFeeCategoryId === k.manageCostId || v.id === k.proFlowFeeCategoryId)
        costDetails.push({
          proFlowFeeCategoryId: k.manageCostId,
          applyType: k.applyType,
          amount: k.amount,
          apv: fee ? fee.apv : k.apv,
          defaultAmt: k.defaultAmt,
          defaultBool: fee ? fee.defaulted : k.defaultBool,
          happenDate: k.happenDate,
          supply: 0,
          supplyRemark: k.supplyRemark,
          visitRecordId: k.visitRecordId,
          visitRecordInfo: k.visitRecordInfo,
          // fileUrl: this.getDesensitizedFileUrl(k),
          fileUrl: k.fileUrl,
          fileArr: this.getFileArr(k.fileList),
          costMin: k.costMin,
          costMax: k.costMax
          // comment: k.comment
        })
      }
      const errIndex = this.fileList.findIndex(item => [0, 2, 4, 6].includes(item.fileStatus))
      const reUploadIndex = this.fileList.findIndex(item => [1].includes(item.fileType))
      if (errIndex > -1) {
        this.$message.error(this.$t('all.autotext1819'))
        return
      }
      if (reUploadIndex > -1) {
        this.$message.error(this.$t('all.autotext1820'))
        return
      }

      const personObj = this.personMap[this.personName]
      this.saveDraftLoading = true

      feeApplySaveDraft({
        proId: this.projectId,
        proFlowId: this.proFlowId,
        orgId: this.centerId,
        userNo: this.personId,
        type: this.type,
        bankId: this.accountId,
        moneyType: this.moneyType,
        applyReason: this.applyReason,
        fileArray: JSON.stringify(this.fileList),
        feeApplyDetails: JSON.stringify(costDetails),
        ptsTypeId: this.ptsTypeId,
        ptsTypeIdDesc: this.ptsTypesList.find(item => {
          return item.id === this.ptsTypeId
        })?.description,
        ptsId: personObj ? personObj.id : '',
        ptsNo: personObj ? personObj.ptsNo : '',
        ptsName: personObj ? personObj.ptsName || personObj.bankName : '',
        visitId: this.versionId,
        assignInfo: JSON.stringify(this.assignInfo)
      })
        .then(res => {
          this.saveDraftLoading = false
          this.$message.success(this.$t('all.autotext1316'))
          // this.$router.go(-1)
          // this.$router.push({ name: 'CostApply' })
        })
        .catch(() => {
          this.saveDraftLoading = false
        })
    },
    getStoreAndSubmitButtonState (loading = false) {
      this.storeAndSubmitButtonState = loading
    },
    handleOrigin (item) {
      this.$refs.detailView.open(item.costId)
    }
  }
}
</script>
<style lang="less" scoped>
.gutter-example .ant-row > div {
  background: transparent;
  border: 0;
}
.gutter-box {
  background: #00a0e9;
  padding: 5px 0;
}
</style>
